package com.example.servicegateway.authentication.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.demo.common.constants.AuthModel;
import com.demo.common.constants.AuthRedisKey;
import com.example.servicegateway.entity.TokenInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Slf4j
@Component(AuthModel.USERNAME_PASSWORD)
public class UsernamePasswordAuthComponent extends AuthComponent {

    @Override
    protected String getRedisTokenKey(String userId) {
        return AuthRedisKey.usernamePasswordTokenKey(userId);
    }

    /**
     * 授权校验
     * @param authority 权限
     * @param path 请求url
     * @return true-授权成功
     */
    @Override
    protected boolean grant(TokenInfo tokenInfo, String authority, String path) {
        String roleId = StringUtils.removeStart(authority,"ROLE_");
        if (StringUtils.equals(roleId, "1")) {
            log.info("超级管理员，放行");
            return true;
        }

        String json = super.stringRedisTemplate.opsForValue().get(AuthRedisKey.usernamePasswordMenuKey(roleId));
        if (StringUtils.isBlank(json)) {
            log.info("角色={}，菜单为空", roleId);
            return false;
        }

        List<Map<String, String>> maps = JSON.parseObject(json, new TypeReference<>() {});
        for (Map<String, String> map : maps) {
            String url = map.get("url");
            String enable = map.get("enable");

            if (StringUtils.equals(url, path) && StringUtils.equals(enable, "1")) {
                log.info("鉴权通过，url：{}", url);
                return true;
            }
        }
        log.info("鉴权不通过，角色id：{}，角色对应的菜单：{}", roleId, maps);
        return false;
    }
}
